<template>
   <div>
    <div v-if="mode === 'DESIGN'">
      <el-icon style="margin-right: 5px;"><LocationInformation /></el-icon>
      <span> {{ placeholder }}</span>
    </div>
    <div v-else-if="mode === 'PC' && !readonly">
      <el-input :disabled="!enableEdit" clearable v-model="_value" :placeholder="placeholder">
        <template #append>
          <el-icon @click="visible = true"><MapLocation /></el-icon>
        </template>
      </el-input>
      <w-dialog :title="'点击地图选择位置：' + position.addr" v-model="visible" @ok="selectOk">
        <div class="v-map" v-if="visible">
          <el-amap :center="center" :zoom="zoom" @click="clickMap" @init="init">
            <el-amap-marker :visible="true" :position="center"/>
            <el-amap-search-box @select="selectPoi"/>
            <el-amap-control-geolocation :visible="true" @complete="getLocation"/>
          </el-amap>
        </div>
      </w-dialog>
    </div>
    <div v-else-if="mode === 'MOBILE' && !readonly" class="m-v-map">
      <field v-model="_value" :readonly="!enableEdit" clearable :placeholder="placeholder">
        <template #right-icon>
          <el-icon @click="selectPosition"><MapLocation /></el-icon>
        </template>
      </field>
      <popup v-model:show="visible" :style="popupStyle" position="left" lazy-render safe-area-inset-bottom>
        <nav-bar placeholder :title="$isNotEmpty(position.addr) ? position.addr : '请选择位置'" left-text="返回"
          right-text="确定" left-arrow @click-left="visible = false" @click-right="selectOk"/>
        <el-amap :center="center" :zoom="zoom" @click="clickMap" @init="init">
          <el-amap-marker :visible="true" :position="center"/>
          <el-amap-search-box @select="selectPoi"/>
          <el-amap-control-geolocation :visible="true" @complete="getLocation"/>
        </el-amap>
      </popup>
    </div>
    <div v-else>
      {{ _value }}
    </div>
  </div>
</template>

<script>
import { LocationInformation, MapLocation } from '@element-plus/icons-vue'
import { Field, Popup, NavBar } from 'vant'
import componentMinxins from '/@/views/setting/workflow/components/ComponentMinxins'
import { toRefs, reactive } from 'vue'
import { isNotEmpty } from '/@/utils/utils'
import VueAMap, { initAMapApiLoader, lazyAMapApiLoaderInstance } from '@vuemap/vue-amap';
import '@vuemap/vue-amap/dist/style.css'
/*高德地图组件初始化*/
initAMapApiLoader({
    key: '54258384f8ac03ec2032977d0a45e678',
    plugin: [
        'AMap.Autocomplete',
        // 'AMap.ElasticMarker',
         'AMap.PlaceSearch',
        /* "AMap.MapType",*/
        "AMap.Geocoder",
        'AMap.Geolocation'
    ],
});
export default {
    name: 'Location',
    mixins: [componentMinxins],
    components: { Field, Popup, NavBar, LocationInformation, MapLocation },
    props: {
        modelValue: {
            efault: null,
        },
        placeholder: {
            type: String,
            default: '请选择地理位置',
        },
        enableEdit: {
            type: Boolean,
            default: false,
        },
    },
    emits: ['update:modelValue'],
    setup() {
        const state = reactive({
            visible: false,
            center: [121.59996, 31.197646],
            zoom: 14,
            position: {
                addr: '',
                zb: [117.120098, 36.6512],
            },
            popupStyle: {
                height: '100%',
                width: '100%',
                background: '#f7f7f9',
            },
            geocoder: null,
            searchOption: {}
        })
        const selectPoi = (e) => {
            console.log(e)
            state.center = [e.poi.location.lng, e.poi.location.lat]
            state.position.zb = state.center
            resolveAddr(state.position.zb)
        }
        const init = (map) => {
            console.log(VueAMap)
            map.plugin('AMap.Geocoder', () => {
                state.geocoder = new VueAMap.Geocoder();
                //map.addControl(this.geocoder);
            })
        }
        const getLocation = (e) => {
            console.log(e)
        }
        const clickMap = (e) => {
            let { lng, lat } = e.lnglat
            state.center = [lng, lat]
            console.log(e)
            state.position.zb = [lng, lat]
            resolveAddr(state.position.zb)
        }
        const resolveAddr = (pos) => {
            state.geocoder.getAddress(pos, (status, result) => {
                if (status === 'complete' && result.info === 'OK') {
                    if (result && result.regeocode) {
                        state.position.addr = result.regeocode.formattedAddress
                        console.log('获取到位置', result.regeocode.formattedAddress)
                    }
                }
            })
        }
        const toLocation = () => {
            if (isNotEmpty(_value.value)) {
                var MSearch = new VueAMap.PlaceSearch(state.searchOption) //构造PlaceSearch类
                VueAMap.event.addListener(MSearch, 'complete', (val) => {
                    if (val.poiList.count > 0) {
                        let center = val.poiList.pois[0]
                        state.center = [center.location.lng, center.location.lat]
                        state.position.zb = [center.location.lng, center.location.lat]
                    }
                }) //返回结果
                MSearch.search(this._value) //关键字查询
            } else {
                getPosition()
            }
        }
        const getPosition = () => {
            var geolocation = new VueAMap.Geolocation({
                enableHighAccuracy: true,
                timeout: 10000,
                position: 'RB',
                panToLocation: true,
                showCircle: true,
                buttonOffset: new VueAMap.Pixel(10, 20),
                zoomToAccuracy: true,
            })
            geolocation.getCurrentPosition(function (status, result) {
                if (status !== 'error') {
                    let lng = result.position.lng
                    let lat = result.position.lat
                    state.position.zb = [lng, lat]
                    state.center = [lng, lat]
                } else {
                    console.log('定位失败，需要https环境')
                }
            })
        }
        const onSearchResult = (pois) => {
            if (pois.length > 0) {
                let center = pois[0]
                state.position.addr = center.name
                state.center = [center.lng, center.lat]
                state.position.zb = [center.lng, center.lat]
            }
        }
        const selectOk = () => {
            _value.value = state.position.addr
            state.visible = false
        }
        const selectPosition = () => {
            state.visible = true
        }
        return {
            ...toRefs(state),
            selectPoi,
            init,
            getLocation,
            clickMap,
            toLocation,
            getPosition,
            onSearchResult,
            selectOk,
            selectPosition
        }
    }
}
</script>

<style lang="scss" scoped>
.v-map {
  width: 100%;
  height: 400px;
  position: relative;
}
</style>